package com.biubiux2.codec.compress;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageCodec;

import java.util.List;

/**
 * @author noexcs
 * @since 8/10/2022 2:00 PM
 */
public class MessageCompressHandler extends MessageToMessageCodec<ByteBuf,ByteBuf> {

    @Override
    protected void encode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {
        byte[] bytes = new byte[msg.readableBytes()];
        msg.readBytes(bytes);
        byte[] compressed = CompressUtil.compress(bytes);
        ByteBuf buffer = PooledByteBufAllocator.DEFAULT.buffer(compressed.length);
        buffer.writeBytes(compressed);
        out.add(buffer);
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {
        byte[] bytes = new byte[msg.readableBytes()];
        msg.readBytes(bytes);
        byte[] decompressed = CompressUtil.decompress(bytes);

        ByteBuf buffer = PooledByteBufAllocator.DEFAULT.buffer(decompressed.length);
        buffer.writeBytes(decompressed);
        out.add(buffer);
    }
}
